package com.jike.shop.cloud;

import com.jike.shop.cloud.model.common.StockInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.*;

import static com.jike.shop.cloud.service.impl.GoodServiceImpl.STOCK_KEY_PREFIX;
import static java.lang.Boolean.FALSE;

@SpringBootApplication
@EnableDiscoveryClient
public class JikeGoodServiceServer implements ApplicationRunner {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private IGoodService goodService;

    public static void main(String[] args) {
        SpringApplication.run(JikeGoodServiceServer.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 商品缓存预热
        StockInfo stock = new StockInfo(1000, 0);

        // 预热1000个商品sku
        for(int i = 1; i <= 1000; i++) {
            String key = STOCK_KEY_PREFIX + i;
            if(FALSE.equals(redisTemplate.hasKey(key))) {
                redisTemplate.opsForValue().set(key, stock);
            }
        }

        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), new ThreadPoolExecutor.CallerRunsPolicy());
        // 启动解锁缓存
        executor.execute(() -> goodService.checkLockStock());
    }
}
